package main

import (
	"context"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/broker"
	"github.com/micro/go-micro/v2/broker/nats"
	"github.com/micro/go-plugins/wrapper/trace/opentracing/v2"
	"github.com/pkg/errors"
	"go-todolist/achievement-srv/repository"
	"go-todolist/achievement-srv/subscriber"
	"go-todolist/common/db"
	"go-todolist/common/tracer"
	"log"
	"time"
)

// 所有port都是服务默认端口，ip请根据实际情况配置
const (
	ServerName = "go.micro.service.achievement"
	MongoUri   = "mongodb://172.18.0.58:27017"
	NatsUri    = "nats://172.18.0.58:4222"
	JaegerAddr = "172.18.0.58:6831"
)

// achievement-srv服务
func main() {
	// 在日志中打印文件路径，便于调试代码
	log.SetFlags(log.Llongfile)

	conn, err := db.ConnectMongo(MongoUri, time.Second)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Disconnect(context.Background())

	// 配置jaeger连接
	jaegerTracer, closer, err := tracer.NewJaegerTracer(ServerName, JaegerAddr)
	if err != nil {
		log.Fatal(err)
	}
	defer closer.Close()
	// New Service
	service := micro.NewService(
		micro.Name(ServerName),
		micro.Version("latest"),
		// 配置nats为消息中间件，默认端口是4222
		micro.Broker(nats.NewBroker(
			// 地址是我本地nats服务器地址，不要照抄
			broker.Addrs(NatsUri),
		)),
		// 配置链路追踪为jaeger
		micro.WrapSubscriber(opentracing.NewSubscriberWrapper(jaegerTracer)),
	)

	// Initialise service
	service.Init()

	// Register Handler
	handler := &subscriber.AchievementSub{
		Repo: &repository.AchievementRepoImpl{
			Conn: conn,
		},
	}
	// 这里的topic注意与task-srv注册的要一致
	if err := micro.RegisterSubscriber("go.micro.service.task.finished", service.Server(), handler); err != nil {
		log.Fatal(errors.WithMessage(err, "subscribe"))
	}

	// Run service
	if err := service.Run(); err != nil {
		log.Fatal(errors.WithMessage(err, "run server"))
	}
}
